import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerGUI extends JFrame {
    private JTextArea logArea;
    private ServerSocket serverSocket;
    // 保存所有客户端的输出流，用于广播
    private final Set<PrintWriter> clientWriters = new HashSet<>(); 
    private ExecutorService threadPool = Executors.newCachedThreadPool();

    public ServerGUI() {
        setTitle("聊天服务器管理界面");
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        logArea = new JTextArea();
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);
        add(scrollPane, BorderLayout.CENTER);

        startServer();
        setVisible(true);
    }

    private void startServer() {
        new Thread(() -> {
            try {
                serverSocket = new ServerSocket(12345);
                log("服务器启动，监听端口12345");
                while (!serverSocket.isClosed()) {
                    Socket socket = serverSocket.accept();
                    threadPool.execute(new ClientHandler(socket)); 
                    log("新客户端连接：" + socket.getInetAddress());
                }
            } catch (IOException e) {
                log("服务器启动失败：" + e.getMessage());
            }
        }).start();
    }

    private void log(String msg) {
        logArea.append(msg + "\n");
        logArea.setCaretPosition(logArea.getDocument().getLength());
    }

    // 处理单个客户端的任务（用 Runnable 更灵活）
    private class ClientHandler implements Runnable {
        private Socket socket;
        private PrintWriter out;
        private BufferedReader in;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // 加锁，把当前客户端的输出流加入集合
                synchronized (clientWriters) {
                    clientWriters.add(out); 
                }

                String message;
                while ((message = in.readLine()) != null) {
                    log("收到消息 [" + socket.getInetAddress() + "]: " + message);
                    // 广播消息给所有客户端
                    broadcast(message); 
                }
            } catch (IOException e) {
                log("客户端断开 [" + socket.getInetAddress() + "]: " + e.getMessage());
            } finally {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    log("关闭连接失败: " + e.getMessage());
                }
                // 从集合移除，避免广播到已断开的客户端
                synchronized (clientWriters) {
                    clientWriters.remove(out); 
                }
            }
        }
    }

    // 广播方法：遍历所有客户端，转发消息
    private void broadcast(String message) {
        synchronized (clientWriters) { 
            for (PrintWriter writer : clientWriters) {
                writer.println(message); 
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ServerGUI::new);
    }
}